import React, { useEffect, useState, useRef } from 'react'
import Head from 'next/head'
import Header from '../header'
import Profile from '../profile'
import { Container, Paper } from '@material-ui/core';
import { makeStyles, Theme } from '@material-ui/core/styles';
import elementResizeDetectorMaker from 'element-resize-detector'
import { debounce,throttle } from '../../utils/ActionUtils'
export const siteTitle = 'Next.js Sample Website'

const useStyles = makeStyles((theme: Theme) => ({
  '@global': {
    body: {
      background: theme.palette.background.default
    }
  },
  header: {
    width: '100vw',
    position: 'fixed',
    top: 0,
    zIndex: 1
  },
  body: {
    paddingTop: '48px'
  },
  container: {
    display: 'flex',
    padding: '0 24px'
  },
  left: {
    position: 'fixed',
    top: '48px'
  },
  right: {
    marginLeft: '25%',
    width: '75%',
    padding: '20px',
    [theme.breakpoints.down('sm')]: {
      marginLeft: '0',
      width: '100%'
    }
  }
}))

function Layout({ children, title = '' }) {
  const classes = useStyles()

  const container = useRef(null)
  const [width, setWidth] = useState(0)
  useEffect(() => {
    const erd = elementResizeDetectorMaker()

    const resize = throttle(() => {
      // 宽度是25% - 15
      const { clientWidth } = container.current
      if (clientWidth < 960) {
        setWidth(0)
      } else {
        setWidth(clientWidth / 4 - 48)
      }
    }, 16)
    erd.listenTo(container.current, resize)
  }, [])

  return (
    <div>
      <Head>
      </Head>
      <header className={classes.header}>
        <Header title={title} />
      </header>
      <div id="back-to-top-anchor"></div>
      <main className={classes.body} >
        <Container ref={container} className={classes.container} maxWidth='lg' disableGutters>
          <div className={classes.left} style={{ width: `${width}px`, display: `${width ? 'block' : 'none'}` }}>
            <Profile />
          </div >
          <Paper className={classes.right}>
            {children}
          </Paper >
        </Container>
      </main>
    </div>
  )
}

export default Layout
